package com.recharge.web.controller;


import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.web.ObjectResponse;
import com.recharge.domain.query.MerchantQueryDO;
import com.recharge.domain.query.ProviderOrderQueryDO;
import com.recharge.domain.vo.MerchantDO;
import com.recharge.domain.vo.UserLoginDO;
import com.recharge.service.MerchantService;
import io.swagger.annotations.ApiOperation;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author reagan
 * @since 2020-08-19
 */
@RestController
@RequestMapping("/merchant")
public class MerchantController extends BaseController {

    @Autowired
    private MerchantService merchantService;

    @RequiresPermissions("merchant:add")
    @RequestMapping(value="/add.html", method = RequestMethod.POST)
    @ApiOperation(value="增加下游商家信息", notes="")
    public @ResponseBody
    ObjectResponse<MerchantDO> add(@RequestBody MerchantDO domain) {

        ObjectResponse<MerchantDO> response = new ObjectResponse<>();

        // 表单验证
        if (!domain.addVerification()){
            response.setStatus(ErrorCode.PARAM_VERIFICATION_ERROR.getCode());
            response.setMsg(ErrorCode.PARAM_VERIFICATION_ERROR.getMsg());
            return response;
        }

        domain.setCreator(getUserName());

        ResultDO result = merchantService.add(domain);

        if(!result.isSuccess()) {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return response;
    }

    @RequiresPermissions("merchant:edit")
    @RequestMapping(value="/edit.html", method = RequestMethod.POST)
    @ApiOperation(value="编辑下游商家信息", notes="")
    public @ResponseBody
    ObjectResponse<MerchantDO> edit(@RequestBody MerchantDO domain) {

        ObjectResponse<MerchantDO> response = new ObjectResponse<>();

        ResultDO result = merchantService.edit(domain);

        if(!result.isSuccess()) {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return response;
    }

    @RequiresPermissions("merchant:get")
    @RequestMapping(value="/get.html", method = RequestMethod.POST)
    @ApiOperation(value="获取下游商家信息", notes="")
    public @ResponseBody
    ObjectResponse<MerchantDO> get(@RequestBody MerchantDO domain) {

        ObjectResponse<MerchantDO> response = new ObjectResponse<>();

        ResultDO result = merchantService.get(domain.getId());

        if(!result.isSuccess()) {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        } else {
            response.setData((MerchantDO) result.getModel(ResultDO.FIRST_MODEL_KEY));
        }
        return response;
    }

    @RequiresPermissions("merchant:getListByProviderId")
    @RequestMapping(value="/getListByProviderId.html", method = RequestMethod.POST)
    @ApiOperation(value="获取下游商家信息", notes="")
    public @ResponseBody
    ObjectResponse<List< MerchantDO>> getListByProviderId(@RequestBody MerchantQueryDO domain) {

        ObjectResponse<List< MerchantDO>> response = new ObjectResponse<>();

        ResultDO result = merchantService.getListByProviderId(domain.getProviderId());

        if(!result.isSuccess()) {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        } else {
            response.setData((List< MerchantDO>) result.getModel(ResultDO.FIRST_MODEL_KEY));
        }
        return response;
    }

    @RequiresPermissions("merchant:delete")
    @RequestMapping(value="/delete.html", method = RequestMethod.POST)
    @ApiOperation(value="删除下游商家信息", notes="")
    public @ResponseBody
    ObjectResponse delete(@RequestBody MerchantDO domain) {

        ObjectResponse response = new ObjectResponse();
        UserLoginDO userLoginDO = getUserLoginInfo();

        ResultDO result = merchantService.remove(domain.getId(), userLoginDO.getUsername());

        if(!result.isSuccess()) {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return response;
    }

    @RequiresPermissions("merchant:resetSecretKey")
    @RequestMapping(value="/resetSecretKey.html", method = RequestMethod.POST)
    @ApiOperation(value="重置下游商家密钥", notes="")
    public @ResponseBody
    ObjectResponse resetSecretKey(@RequestBody MerchantDO domain) {

        ObjectResponse response = new ObjectResponse();
        UserLoginDO userLoginDO = getUserLoginInfo();

        ResultDO result = merchantService.resetSecretKey(domain.getId(), userLoginDO.getUsername());

        if(!result.isSuccess()) {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }
        return response;
    }


    @RequiresPermissions("merchant:page")
    @RequestMapping(value="/page.html", method = RequestMethod.POST)
    @ApiOperation(value="分页查询下游商家", notes="")
    public @ResponseBody  ObjectResponse<PageDO> page(@RequestBody MerchantQueryDO query) {

        ObjectResponse<PageDO> response = new ObjectResponse<>();

//        ResultDO result = merchantService.findListInfo(query);
        query.setId(getUserMerchantId());
        ResultDO result = merchantService.find(query);

        if(result.isSuccess()) {
            response.setData((PageDO) result.getModel(ResultDO.FIRST_MODEL_KEY));
        } else {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }

        return response;
    }

    @RequiresPermissions("merchant:page")
    @RequestMapping(value="/pageInfo.html", method = RequestMethod.POST)
    @ApiOperation(value="分页查询下游商家(包含余额)", notes="")
    public @ResponseBody  ObjectResponse<PageDO> pageInfo(@RequestBody MerchantQueryDO query) {

        ObjectResponse<PageDO> response = new ObjectResponse<>();

        query.setId(getUserMerchantId());
        ResultDO result = merchantService.findListInfo(query);

        if(result.isSuccess()) {
            response.setData((PageDO) result.getModel(ResultDO.FIRST_MODEL_KEY));
        } else {
            response.setStatus(result.getErrorCode().getCode());
            response.setMsg(result.getErrorCode().getMsg());
        }

        return response;
    }

    @RequiresPermissions("merchant:download")
    @RequestMapping(value="/download.html", method = RequestMethod.POST)
    @ApiOperation(value="一键商户数据下载", notes="")
    public void download(@RequestBody MerchantQueryDO query, HttpServletResponse response) {
        try{
            ResultDO result = merchantService.getMerchantInfo(query.getId());
            String str = (String) result.getModel(ResultDO.FIRST_MODEL_KEY);
            // 设置文件名
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("商户信息.txt" ,"UTF-8"));
            // 写出文件
            OutputStream os = new BufferedOutputStream( response.getOutputStream() );
            // 输出
            os.write(str.getBytes("UTF-8"));
            // 关闭和刷新管道，不然可能会出现表格数据不齐，打不开之类的问题
            os.flush();
            os.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
